﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace PS3Packager.CustomControls
{
    public class ExtendedErrorProvider : ErrorProvider
    {
        public ExtendedErrorProvider()
        {
        }

        public ExtendedErrorProvider(ContainerControl parentControl)
            : base(parentControl)
        {
        }

        public ExtendedErrorProvider(System.ComponentModel.IContainer container)
            : base(container)
        {
        }

        private IEnumerable<Control> GetChildControls(Control.ControlCollection container)
        {
            List<Control> result = new List<Control>();

            foreach (Control c in container)
            {
                result.AddRange(GetChildControls(c.Controls));
                result.Add(c);
            }

            return result;
        }

        public bool HasErrors()
        {
            IEnumerable<Control> allcontrols = GetChildControls(this.ContainerControl.Controls);

            foreach (Control c in allcontrols)
            {
                if (!string.IsNullOrEmpty(this.GetError(c)))
                {
                    return true;
                }
            }

            return false;
        }
        
        public new void SetError(Control control, string value)
        {
            bool HadErrors = HasErrors();
            
            base.SetError(control, value);

            bool newstate = HasErrors();
            if (HadErrors != newstate)
            {
                ErrorStateChanged(this, newstate);
            }
        }

        public delegate void ErrorStateChangedHandler(ExtendedErrorProvider sender, bool haserrors);
        public event ErrorStateChangedHandler ErrorStateChanged;
    }
}
